package lc.q51_100;


import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * 给定一个二叉树，返回它的中序 遍历。
 */
public class Q94 {
    public List<Integer> inorderTraversal(TreeNode root) {
        // 二叉搜索树的定义是，left < root < right
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        } else {
            // 遍历左子树
            list.addAll(inorderTraversal(root.left));
            // 遍历右子树
            list.add(root.val);
            list.addAll(inorderTraversal(root.right));
        }
        return list;
    }

    // 如何非递归的完成
    public List<Integer> inorderTraversal2(TreeNode root) {
        // 二叉搜索树的定义是，left < root < right
        // 如何使用栈？
        Deque<TreeNode> stack = new ArrayDeque<>();
        List<Integer> list = new ArrayList<>();
        while (root != null || !stack.isEmpty()) {
            // 将所有的左节点都放进栈里
            while (root != null) {
                stack.addFirst(root);
                root = root.left;
            }
            TreeNode node = stack.removeFirst();
            list.add(node.val);
            root = node.right;
        }
        return list;
    }

    // 不递归，也不用栈
    public List<Integer> inorderTraversal3(TreeNode root) {
        // 莫里斯遍历，重点记住
        List<Integer> results = new ArrayList<>();
        TreeNode current = root;
        while (current != null) {
            if (current.left == null) {
                results.add(current.val);
                current = current.right;
            } else {
                // 寻找左节点的最右节点
                TreeNode left = current.left;
                TreeNode newC = current.left;
                while (newC.right != null) {
                    newC = newC.right;
                }
                newC.right = current;
                current.left = null;
                current = left;
            }
        }
        return results;
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        node.left = null;
        node.right = new TreeNode(2);
        node.right.left = new TreeNode(3);
        System.out.println(new Q94().inorderTraversal3(node));
    }

}
